package com.example.lenovo.weiyi;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.com.ruanmeng.demon.VersionM;
import com.com.ruanmeng.utils.CommonUtil;
import com.com.ruanmeng.utils.PreferencesUtils;
import com.com.ruanmeng.utils.UpdateService;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;

/**
 * Created by Administrator on 2017/5/5.
 */

public class SettingActivity extends BaseActivity {
    @BindView(R.id.pc_title)
    View pc_title;
    @BindView(R.id.ll_change_psw)
    LinearLayout llChangePsw;
    @BindView(R.id.ll_yijian_fankui)
    LinearLayout llYijianFankui;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.ll_banben_update)
    LinearLayout llBanbenUpdate;
    @BindView(R.id.ll_about_us)
    LinearLayout llAboutUs;
    @BindView(R.id.ll_yinsi_tiaokuan)
    LinearLayout llYinsiTiaokuan;
    @BindView(R.id.btn_logout)
    Button btnLogout;
    private Request<String> mRequest;
    private Intent intent;
    private TextView tv_cancel;
    private TextView tv_exit;
    private VersionM modelver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        ChangLayTitle("设置");
        AddActivity(this);
        tvVersion.setText(getVersionName(this));
        getData();
    }

    private void getData() {

    }

    @OnClick({R.id.ll_change_psw, R.id.ll_yijian_fankui, R.id.ll_banben_update, R.id.ll_about_us, R.id.ll_yinsi_tiaokuan, R.id.btn_logout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_change_psw:
                intent = new Intent(SettingActivity.this, ChangePswActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.next_in, R.anim.next_out);
                break;
            case R.id.ll_yijian_fankui:
                intent = new Intent(SettingActivity.this, YiJianFanKuiActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.next_in, R.anim.next_out);
                break;
            case R.id.ll_banben_update:
                getVersionData();
                break;
            case R.id.ll_about_us:
                intent = new Intent(SettingActivity.this, AboutusActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.next_in, R.anim.next_out);
                break;
            case R.id.ll_yinsi_tiaokuan:
                intent = new Intent(SettingActivity.this, XieYiActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.next_in, R.anim.next_out);
                break;
            case R.id.btn_logout:
                ShowPopLogout();
                break;
        }
    }

    /**
     * 退出
     */
    public void ShowPopLogout() {
        // 加载布局
        LayoutInflater inflater = LayoutInflater
                .from(SettingActivity.this);
        View view = inflater.inflate(R.layout.dialog_layout, null);
        tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
        tv_exit = (TextView) view.findViewById(R.id.tv_exit);
        // 创建popupwindow对话框
        final PopupWindow pop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setFocusable(true);// 必须有，因为要获得焦点进行输入
        // 设置此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());
        // 点击其他除了popupwindow对话框的地方就可使popupwindow对话框消失
        pop.setOutsideTouchable(true);
        //pop.showAtLocation(liFr, Gravity.CENTER, 0, 0);// 显示位置以某控件为中心
        if (android.os.Build.VERSION.SDK_INT >= 24) {
            int[] a = new int[2];
            pc_title.getLocationInWindow(a);
            pop.showAtLocation((SettingActivity.this).getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, a[1] + pc_title.getHeight());
        } else {
            pop.showAsDropDown(pc_title);
        }
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop.dismiss();
            }
        });
        tv_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 请求接口
//                getLoginOutData();
                pop.dismiss();
                setcleardata();
                clearActivity();
                clearMainActivity();
                startActivity(LoginActivity.class);
            }
        });
    }

    /**
     * 退出登录
     */
//    public void getLoginOutData() {
//        loading();
//        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.LoginOut, Const.POST);
//        mRequest.add("token", PreferencesUtils.getString(SettingActivity.this, "uid"));
//        // 添加到请求队列
//        CallServer.getRequestInstance().add(SettingActivity.this, 0, mRequest,
//                new CustomHttpListener(SettingActivity.this, true, LoginOutM.class) {
//                    @Override
//                    public void doWork(Object data, boolean isOne) {
//                        LoginOutM model = ((LoginOutM) data);
//                        CommonUtil.showToask(SettingActivity.this, model.getMsg());
//                        PreferencesUtils.putInt(SettingActivity.this, "Login", 0);//登录标记
//                        startActivity(LoginActivity.class);
//                    }
//
//                    @Override
//                    public void onFinally(JSONObject obj) throws JSONException {
//                        super.onFinally(obj);
//                        dismiss();
//                    }
//                }, true, false);
//    }
    public void setcleardata() {
        PreferencesUtils.putString(SettingActivity.this, "user_name", "");
//        PreferencesUtils.putString(SettingActivity.this, "phone", "");
        PreferencesUtils.putString(SettingActivity.this, "psw", "");
        PreferencesUtils.putString(SettingActivity.this, "enable", "");
        PreferencesUtils.putString(SettingActivity.this, "salt", "");
        PreferencesUtils.putString(SettingActivity.this, "danwei", "");
        PreferencesUtils.putString(SettingActivity.this, "bumen", "");
        PreferencesUtils.putString(SettingActivity.this, "email", "");
        PreferencesUtils.putString(SettingActivity.this, "statues", "");
        PreferencesUtils.putString(SettingActivity.this, "url", "");
        PreferencesUtils.putString(SettingActivity.this, "uid", "");
        PreferencesUtils.putString(SettingActivity.this, "age", "");
        PreferencesUtils.putString(SettingActivity.this, "statues", "");
        PreferencesUtils.putString(SettingActivity.this, "IsQD", "");
        PreferencesUtils.putString(SettingActivity.this, "qcard", "");
        PreferencesUtils.putInt(SettingActivity.this, "Login", 0);//登陆标记
    }

    public void getVersionData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.UpdateVersion, Const.POST);
        // 添加到请求队列
        CallServer.getRequestInstance().add(SettingActivity.this, 0, mRequest,
                new CustomHttpListener(SettingActivity.this, true, VersionM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        modelver = ((VersionM) data);
                        if (getVersionName(SettingActivity.this).equals(modelver.getObject().getVersionNo())) {
                            CommonUtil.showToask(SettingActivity.this, "当前已是最新版本");
                        } else {
                            Version();
                        }
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                    }
                }, true, true);
    }

    /**
     * 版本名
     */
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    /**
     * 版本更新
     */
    public void Version() {
        // 解析xml
        View view = View.inflate(SettingActivity.this,
                R.layout.setting_custom_dialog, null);
        TextView text_dialog = (TextView) view.findViewById(R.id.text_dialog);
        text_dialog.setText("检测到新版本，是否更新？");
        // 对话框
        final Dialog dialog = new AlertDialog.Builder(SettingActivity.this)
                .create();
        dialog.show();
        dialog.getWindow().

                setContentView(view);

        // 取消按钮
        TextView btn_Cancel = (TextView) view.findViewById(R.id.cancle);
        btn_Cancel.setOnClickListener(new View.OnClickListener() {
                                          @Override
                                          public void onClick(View v) {
                                              dialog.dismiss();
                                          }
                                      }

        );
        // 确定按钮
        TextView btn_OK = (TextView) view.findViewById(R.id.sure);
        btn_OK.setOnClickListener(new View.OnClickListener() {
                                      @Override
                                      public void onClick(View v) {
                                          dialog.dismiss();
                                          Intent intent1 = new Intent();
                                          intent1.setClass(SettingActivity.this, UpdateService.class);
                                          intent1.putExtra("versionCode", modelver.getObject().getVersionNo());
                                          intent1.putExtra("url", modelver.getObject().getUrl());
                                          SettingActivity.this.startService(intent1);
                                      }
                                  }

        );


    }

}
